<template>
  <div>
    <el-form ref="queryForm" class="query-form" :model="queryParams" size="small" inline>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" size="small" @change="handleQuery">
          <el-option label="全部" :value="0" />
          <el-option label="开启" :value="1" />
          <el-option label="关闭" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="权益包" prop="p_id">
        <el-select v-model="queryParams.p_id" @change="handleQuery">
          <el-option label="全部" :value="null"/>
          <el-option v-for="item in packagesOptions" :key="item.package_id"
            :label="item.name"
            :value="item.package_id" />
        </el-select>
      </el-form-item>
      <el-form-item label="项目" prop="app_id">
        <el-select v-model="queryParams.app_id" placeholder="请选择" @change="handleQuery">
          <el-option v-for="itemb in permission_projectList" :key="itemb.app_id"
            :label="itemb.name"
            :value="itemb.app_id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="版本范围">
        <el-input v-model="queryParams.version" placeholder="用,分割版本"></el-input>
      </el-form-item>
      <el-form-item class="big-query" label="体验券名称">
        <el-input v-model="queryParams.keyword" placeholder="体验券名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="handleQuery">搜索</el-button>
      </el-form-item>
    </el-form>
    <el-button type="primary"
      icon="el-icon-plus"
      style="margin-bottom:10px"
      size="small"
      @click="handleAdd">新增</el-button>
    <el-table v-loading="listLoading" :data="tableData">
      <el-table-column label="体验券名称"
        min-width="120"
        prop="name" />
      <el-table-column label="对应权益包"
        min-width="120"
        prop="pkg_name"/>
      <el-table-column label="版本范围" min-width="200">
        <template slot-scope="scope">
          <p v-for="item in scope.row.project" :key="item.app_id">{{item.app_id|translateToName(permission_projectList,'app_id','name')}}：{{item.version}}</p>
        </template>
      </el-table-column>
      <el-table-column label="状态" min-width="80">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'"
            disable-transitions>{{ scope.row.status === 1 ? '开启' : '关闭' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作"
        width="150"
        fixed="right"
        class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="small"
            type="text"
            @click="handleUpdateStatus(scope.row)">{{ scope.row.status === 1 ? '关闭' : '开启' }}</el-button>
          <el-button
            size="small"
            type="text"
            @click="handleEdit(scope.row)">编辑</el-button>
          <el-button
            size="small"
            type="text"
            @click="handleDetail(scope.row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0"
      :total="total"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.page_size"
      @pagination="getList" />
    <el-dialog :title="!form.id?'新增体验券':'编辑体验券'"
      :visible.sync="addDialogShow"
      width="650px"
      :close-on-click-modal="false"
      @closed="onAddDialogClose">
      <el-form label-width="100px" class="input-form-400" :model="form" :rules="rules" ref="form">
        <el-form-item label="体验券ID" prop="id" required v-if="form.id">
          <span>{{form.id}}</span>
        </el-form-item>
        <el-form-item label="体验券名称" prop="name">
          <el-input v-model="form.name" @blur="form.name=$event.target.value.trim()"></el-input>
        </el-form-item>
        <el-form-item label="体验券时长" prop="minutes">
          <el-row>
            <el-col :span="11">
              <el-input-number v-model="form.minutes" :min="1" :max="9" :precision="0"></el-input-number>
            </el-col>
            <el-col :span="8">
              <el-select v-model="form.cell">
                <el-option label="天" :value="2" />
                <el-option label="分钟" :value="1" />
              </el-select>
            </el-col>
          </el-row>

        </el-form-item>
        <el-form-item label="权益包" prop="p_id">
          <el-select v-model="form.p_id"
            placeholder="请选择"
            filterable>
            <el-option v-for="item in packagesOptions" :key="item.package_id" :label="item.name" :value="item.package_id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-row v-for="(item,index) in form.project" :key="index">
          <el-col :span="10">
            <el-form-item label="项目版本" :prop="'project.'+index+'.app_id'" :rules="{required: true, message: '项目不能为空', trigger: 'blur'}">
              <el-select v-model="item.app_id" placeholder="请选择">
                <el-option v-for="itemb in permission_projectList" :key="itemb.app_id"
                  :label="itemb.name"
                  :value="itemb.app_id"
                  :disabled="disabledChoose(itemb,index)"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="" label-width="10px" :prop="'project.'+index+'.version'" :rules="{required: true, message: '版本不能为空', trigger: 'blur'}">
              <el-input style="width:270px" v-model.trim="item.version" placeholder="版本范围（用,分割版本）"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-button type="text" icon="el-icon-remove-outline" :disabled="form.project.length<2" @click="delProject(index)"></el-button>
            <el-button type="text" icon="el-icon-circle-plus-outline" v-show="index===form.project.length-1" @click="addProject"></el-button>
          </el-col>
        </el-row>
        <el-form-item label="状态" required prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">开启</el-radio>
            <el-radio :label="2">关闭</el-radio>
          </el-radio-group>
          <div>关闭仅对修改后的券有效，已发放的体验券依然有效</div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="onSubmitAdd" :loading="saveLoading">确 认</el-button>
        <el-button @click="addDialogShow = false">取 消</el-button>
      </div>
    </el-dialog>
    <detail-dialog :visible.sync="detailDialogShow" :detailObj="detailObj"/>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
import detailDialog from './components/detail.vue'
import { listRightPackage } from '@/api/rights/package'
import { experienceList, createExperience, updateExperience } from '@/api/experience'
export default {
  name: 'ExperienceList',
  components: {
    detailDialog
  },
  data () {
    return {
      packagesOptions: [],
      listLoading: false,
      saveLoading: false,
      addDialogShow: false,
      detailDialogShow: false,
      queryParams: {
        status: 0,
        p_id: null,
        app_id: null,
        version: '',
        page: 1,
        page_size: 20,
        keyword: ''
      },
      form: {
        id: null,
        'name': '',
        'minutes': undefined,
        'p_id': null,
        cell: 2,
        'project': [
          {
            'app_id': null,
            'version': ''
          }
        ],
        version: '',
        status: 2 // 状态
      },
      tableData: [],
      total: 0,
      detailObj: {},
      rules: {
        name: [
          { required: true, message: '请输入体验券名称', trigger: 'blur' }
        ],
        minutes: [
          { required: true, message: '体验券时长不能为空', trigger: 'blur' }
        ],
        p_id: [
          { required: true, message: '权益包不能为空', trigger: 'change' }
        ],
        version: [
          { required: true, message: '版本不能为空', trigger: 'blur' }
        ]
      }

    }
  },
  computed: {
    ...mapGetters('zcsd-core', ['permission_projectList']),
    disabledChoose () {
      return function (item, index) {
        let findItemIndex = this.form.project.findIndex(item2 => item2.app_id === item.dictValue)
        return findItemIndex !== -1 && index !== findItemIndex
      }
    }
  },
  async created () {
    listRightPackage({ page: 1, page_size: 100, status: 1 }).then(res => {
      this.packagesOptions = res.data.list || []
    })
    this.getList()
  },
  methods: {
    handleQuery () {
      this.queryParams.page = 1
      this.getList()
    },
    getList () {
      this.listLoading = true
      experienceList(this.queryParams).then(res => {
        const data = res.data || {}
        this.tableData = (data.list || []).map(item => {
          (item.project || []).map(it => {
            it.version = it.version.join(',')
          })
          return item
        })
        this.total = data.count
      }).finally(() => {
        this.listLoading = false
      })
    },
    handleUpdateStatus (row) {
      const cStatus = row.status === 1 ? 2 : 1
      const cStatusText = row.status === 1 ? '关闭' : '开启'
      this.$confirm(`是否${cStatusText}“${row.name}?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateExperience({
          id: row.id,
          status: cStatus
        }).then(() => {
          this.$message({
            type: 'success',
            message: cStatusText + '成功!'
          })
          row.status = cStatus
        })
      })
    },
    handleEdit (row) {
      this.addDialogShow = true
      this.$nextTick(() => {
        const obj = JSON.parse(JSON.stringify(row))
        Object.keys(this.form).forEach(key => {
          this.form[key] = obj[key]
        })
        if (obj.minutes >= 1440) {
          this.form.minutes = obj.minutes / 24 / 60
        }
      })
    },
    handleAdd () {
      this.addDialogShow = true
    },
    onAddDialogClose () {
      this.$refs.form.resetFields()
      this.form.project = [{
        'app_id': null,
        'version': ''
      }]
      this.form.id = null
    },
    handleDetail (row) {
      this.detailObj = row
      this.detailDialogShow = true
    },
    addProject () {
      this.form.project.push({
        'app_id': null,
        'version': ''
      })
    },
    delProject (i) {
      this.form.project.splice(i, 1)
    },
    onSubmitAdd () {
      this.$refs.form.validate(valid => {
        if (valid) {
          const project = []
          const params = {
            name: this.form.name,
            status: this.form.status,
            p_id: this.form.p_id,
            cell: this.form.cell
          }
          for (const item of this.form.project) {
            project.push({ app_id: item.app_id, version: item.version.split(',') })
          }
          params.project = project
          if (this.form.cell === 2) {
            params.minutes = this.form.minutes * (24 * 60)
          } else {
            params.minutes = this.form.minutes
          }
          this.saveLoading = true
          if (this.form.id) {
            this.onUpdate(params)
          } else {
            this.onCreate(params)
          }
        }
      })
    },
    onCreate (params) {
      createExperience(params).then(() => {
        this.getList()
        this.$message({
          type: 'success',
          message: '创建成功'
        })
        this.addDialogShow = false
      }).finally(() => {
        this.saveLoading = false
      })
    },
    onUpdate (params) {
      params.id = this.form.id
      updateExperience(params).then(() => {
        this.getList()
        this.$message({
          type: 'success',
          message: '修改成功'
        })
        this.addDialogShow = false
      }).finally(() => {
        this.saveLoading = false
      })
    }
  }
}
</script>
